<template>
  <div class="cavas_box">
    <canvas id="canvasDom" ref="canvasDom" width="662" height="710"></canvas>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, Ref, ref } from 'vue'
import { drawRect, textLineFeed, textReturnOption } from './shapes'
const canvasDom: Ref<HTMLCanvasElement | null> = ref(null)
const ctx: Ref<CanvasRenderingContext2D | null> = ref(null)

onMounted(() => {
  nextTick(() => {
    drawCanvas()
  })
})
async function drawCanvas() {
  ctx.value = canvasDom.value!.getContext('2d')
  if (!ctx.value) return
  await drawRect(ctx.value, {
    x: 0,
    y: 0,
    width: 662,
    height: 710,
    cornerRadius: 15,
    color: '#fff',
  })

  ctx.value.save()
  await drawRect(ctx.value, {
    x: 40,
    y: 30,
    width: 580,
    height: 330,
    cornerRadius: 15,
  })
  ctx.value.clip()
  let img1 = (await getImage(
    'https://images.591wsh.com/2022/10/25/thumb_1666676311900.jpg'
  )) as CanvasImageSource
  ctx.value.drawImage(img1, 40, 30, 580, 330)
  ctx.value.restore()

  textLineFeed(ctx.value, {
    x: 40,
    y: 370,
    width: 560,
    text: '此处是标题，问一个很严肃的问题quitter帅嘛?我觉得还是比较帅的canvas的2d对象，t：绘制的文字，x,y:文字坐标',
    size: 35,
    color: '#333',
    line: 2,
  })
  let price1: textReturnOption = await textLineFeed(ctx.value, {
    x: 40,
    y: 465,
    text: '￥2.',
    size: 40,
    color: 'red',
  })
  let price2 = await textLineFeed(ctx.value, {
    x: price1.x + price1.width,
    y: 475,
    text: '00',
    size: 30,
    color: 'red',
  })

  let price3 = await textLineFeed(ctx.value, {
    x: price2.x + price2.width + 10,
    y: 475,
    text: '￥4.00',
    size: 30,
    color: '#ccc',
    textDecoration: 'line-through',
  })

  let text1 = await textLineFeed(ctx.value, {
    x: 40,
    y: 580,
    text: '长按或扫描识别二维码',
    size: 25,
    color: '#ccc',
  })
  let img2: CanvasImageSource = (await getImage(
    'https://images.591wsh.com/2022/05/11/1652259833211.png'
  )) as HTMLImageElement
  ctx.value.drawImage(img2, 450, 520, 150, 150)
}

// 获取图片完成加载后的实例对象
function getImage(imgSrc: string) {
  return new Promise((resolve, reject) => {
    let img = new Image()
    img.src = imgSrc
    img.crossOrigin = 'anonymous'
    img.onload = function () {
      resolve(img as HTMLImageElement)
    }
  })
}
</script>

<style lang="scss" scoped>
.cavas_box {
  padding-top: 50px;
  display: flex;
  justify-content: center;
}
#canvasDom {
  width: 331px;
  height: 350px;
}
</style>
